package code.zzl.monitor.sdk.push.impl;

import code.zzl.monitor.sdk.model.LogMessage;
import code.zzl.monitor.sdk.push.IPush;
import code.zzl.monitor.constant.RedissonConstant;
import org.redisson.Redisson;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ Author 龙
 * @ Date 2024-07-31 12:47
 * @ Description: 发布订阅方式进行推送消息
 */
public class RedisPush implements IPush {

    private final Logger logger = LoggerFactory.getLogger(RedisPush.class);

    private RedissonClient redissonClient;

    @Override
    public void open(String host, int port, String password) {
        if (null != redissonClient && !redissonClient.isShutdown()) return;
        Config config = new Config();
        config.setCodec(JsonJacksonCodec.INSTANCE);
        config.useSingleServer()
                .setAddress("redis://" + host + ":" + port)
                .setPassword(password)
                .setConnectionPoolSize(64)
                .setConnectionMinimumIdleSize(10)
                .setIdleConnectionTimeout(1000)
                .setConnectTimeout(1000)
                .setRetryAttempts(3)
                .setRetryInterval(1000)
                .setPingConnectionInterval(0)
                .setKeepAlive(true);
        logger.info("业务监控创建redissonClient客户端完成! ");
        this.redissonClient = Redisson.create(config);

    }

    @Override
    public void send(LogMessage logMessage) {
        try {
            RTopic topic = redissonClient.getTopic(RedissonConstant.TOPIC_SDK_KEY);
            topic.publish(logMessage);
        } catch (Exception e) {
            logger.error("警告: 业务行为监控组件，推送日志消息失败: ", e);
        }
    }
}
